﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Services;
using XfTech.SmartTms.IServices;
using IdentityModel;
using System.Net.Http;
using IdentityModel.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp;
using Volo.Abp.Caching;
using Microsoft.Extensions.Caching.Distributed;
using XfTech.SmartTms.Users.Dtos;

namespace XfTech.SmartTms.Services
{
    /// <summary>
    /// 用户模块接口
    /// </summary>
    public class UserAppService : SmartTmsAppService, IUserAppService
    {
        private readonly IConfiguration _configuration;
        private readonly IDistributedCache<string> _distributedCache;

        public UserAppService(IConfiguration configuration, IDistributedCache<string> distributedCache)
        {
            _configuration = configuration;
            _distributedCache = distributedCache;
        }

        /// <summary>
        /// 登录获取Token
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<string> GetUserTokenAsync(UserLoginDto input)
        {

            _distributedCache.Set("wangxuefneg", "123", new DistributedCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromMinutes(5) //5分钟后过期
            }); ;

            string code = _distributedCache.Get("wangxuefneg");



            var client = new HttpClient();//定义Http客户端
            var disco = await client.GetDiscoveryDocumentAsync(_configuration["AuthServer:Authority"]);

            var tokenClient = new TokenClient(client, new TokenClientOptions
            {
                Address = disco.TokenEndpoint,                  //访问Ids4的令牌地址
                ClientId = _configuration["AuthServer:AppId"],  //clientId
                ClientSecret = _configuration["AuthServer:AppSecret"] //clientSecret
            });

            var tokenResponse = await tokenClient.RequestPasswordTokenAsync(input.UserName, input.Password, "SmartTms");

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return string.Empty;
            }

            return tokenResponse.Json.ToString();
        }
    }
}
